package com.itshops.dao.impl;

import com.itshops.dao.ProductDao;
import com.itshops.entity.Product;
import com.itshops.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    @Override
    public long selectCountBytId(String tId) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select count(1) from product where t_id = ?";
        long query =(long) queryRunner.query(sql, new ScalarHandler(), tId);
        return query;
    }

    @Override
    public List<Product> selectProductByPage(int page, int pagesize, String tId) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select p_id as pid,t_id as tid,p_name as pname,p_time as ptime ," +
                "p_image as pimage,p_state as pstate ,p_info as pinfo ,p_rice as pprice " +
                "from product where t_id = ? limit ?,?;";
        List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class),
                tId, (page - 1) * pagesize, pagesize);
        return list;
    }

    @Override
    public Product selectProductByPid(String pId) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select p_id as pid,t_id as tid,p_name as pname,p_time as ptime ," +
                "p_image as pimage,p_state as pstate ,p_info as pinfo ,p_rice as pprice " +
                "from product where p_id = ?;";
        Product query = queryRunner.query(sql, new BeanHandler<Product>(Product.class),pId);
        return query;
    }

}
